<?php
namespace StarCloud\Models;

trait UserTrait
{
    /**
     * 生成10位数字uid，每次生成10个uid随机数，查询数据库一次
     */
    public static function generateUid($try = 1)
    {
        $triedTimes = 0;
        while ($triedTimes < $try) {
            $randUids = [];
            for ($i = 0; $i < 10; ++$i) {
                $randUids[] = mt_rand(self::UID_MIN, self::UID_MAX);
            }

            $existedUids = array_column(
                self::find([
                    'columns' => self::UID_FIELD,
                    'conditions' => self::UID_FIELD . ' IN' . self::implodeIntArrayToString($randUids),
                ])->toArray(),
                self::UID_FIELD
            );

            $availableUids = array_diff($randUids, $existedUids);
            if (!empty($availableUids)) {
                return array_pop($availableUids);
            }

            ++$triedTimes;
        }

        throw new Exception('10001');
    }
}
